<template>
  <div v-if="userStore.token">
    <el-container>
      <el-aside width="200px" style="background: #f5f7fa">
        <el-menu :default-active="$route.path" router>
          <template v-for="route in menuRoutes" :key="route.path">
            <el-sub-menu v-if="route.children && route.children.length > 0" :index="route.path">
              <template #title>
                <el-icon><component :is="getIcon(route.meta?.icon)" /></el-icon>
                <span>{{ route.meta?.title || '未命名' }}</span>
              </template>
              <el-menu-item 
                v-for="childRoute in route.children" 
                :key="childRoute.path"
                :index="route.path + '/' + childRoute.path"
              >
                <span>{{ childRoute.meta?.title || '未命名' }}</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="route.path">
              <el-icon><component :is="getIcon(route.meta?.icon)" /></el-icon>
              <span>{{ route.meta?.title || '未命名' }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header class="erp-header">
          <div class="erp-header-left">
            <img src="/favicon.ico" alt="logo" class="erp-logo" />
            <span class="erp-title">智芯ERP管理系统</span>
          </div>
          <div class="erp-header-right">
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ userStore.userInfo?.realName || '未登录' }}
                <el-icon><User /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goProfile">个人信息</el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main style="background:#f0f2f5;min-height:100vh;padding:0;">
          <div class="erp-main-full">
            <RouterView />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <RouterView v-else />
</template>

<script setup>
import { RouterView, useRouter } from 'vue-router'
import routes from '@/router/modules/erp'
import { hasPerm } from '@/utils/permission'
import { useUserStore } from '@/store/user'
import { 
  User, 
  House, 
  List, 
  ShoppingCart, 
  Tools, 
  Money, 
  Setting,
  Document
} from '@element-plus/icons-vue'
import { onMounted, computed } from 'vue'

const userStore = useUserStore()
const router = useRouter()

// 从localStorage恢复用户数据
onMounted(() => {
  userStore.restoreFromStorage()
})

// 计算属性：根据权限过滤菜单路由
const menuRoutes = computed(() => {
  if (!Array.isArray(routes)) return []
  
  return routes.filter(route => {
    // 确保route是有效对象
    if (!route || typeof route !== 'object') {
      return false
    }
    
    // 隐藏不需要显示在菜单中的路由
    if (route.meta?.hidden) {
      return false
    }
    
    // 检查是否有权限访问该路由
    if (route.meta?.perm && !hasPerm(route.meta.perm)) {
      return false
    }
    
    // 如果有子路由，递归过滤
    if (route.children && Array.isArray(route.children) && route.children.length > 0) {
      const filteredChildren = route.children.filter(child => {
        if (!child || typeof child !== 'object') {
          return false
        }
        
        if (child.meta?.hidden) {
          return false
        }
        
        if (child.meta?.perm && !hasPerm(child.meta.perm)) {
          return false
        }
        
        return true
      })
      
      // 如果过滤后没有子路由，也不显示父级
      return filteredChildren.length > 0
    }
    
    return true
  })
})

function getIcon(iconName) {
  if (!iconName) return 'Document'
  
  // 图标映射
  const iconMap = {
    'home': 'House',
    'task': 'List',
    'customer': 'User',
    'purchase': 'ShoppingCart',
    'production': 'Tools',
    'finance': 'Money',
    'report': 'Document',
    'product': 'Document',
    'basic': 'Setting',
    'system': 'Setting'
  }
  
  return iconMap[iconName] || 'Document'
}

function logout() {
  userStore.clearUserData()
  router.push('/login')
}

function goProfile() {
  router.push('/profile')
}
</script>

<style scoped>
.erp-header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.erp-header-left {
  display: flex;
  align-items: center;
}

.erp-logo {
  width: 32px;
  height: 32px;
  margin-right: 10px;
}

.erp-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.erp-header-right {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #606266;
}

.el-dropdown-link:hover {
  color: #409eff;
}

.erp-main-full {
  height: 100%;
  width: 100%;
}

/* 全屏样式 */
:deep(.el-main) {
  padding: 0 !important;
}

:deep(.el-container) {
  height: 100vh;
}

:deep(.el-aside) {
  height: 100vh;
  overflow-y: auto;
}

:deep(.el-menu) {
  border-right: none;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

:deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
}
</style>
